//
//  KLGoodDetailViewController.m
//  KunLun
//
//  Created by Mac on 2017/11/27.
//  Copyright © 2017年 stoneobs@icloud.com. All rights reserved.
//

#import "KLGoodDetailViewController.h"
#import "KLGoodDetailHeaderView.h"
#import "KLGoodDetailBoomView.h"
#import "KLCommentTableViewCell.h"
#import "KLGoodBuyDetailViewController.h"
#import "KLGoodDetailModel.h"
#import "KLCommentModel.h"
#import "KLBuyNowViewController.h"
#import "KLSepeedBuyViewController.h"
#import "KLSharePresentController.h"
@interface KLGoodDetailViewController ()<KLGoodDetailHeaderViewDelegate>
@property(nonatomic, strong) UIImageView                            *bannerImageView;
@property(nonatomic, strong)  STAdvertingScrollView     *adverView;
@property(nonatomic, strong) KLGoodDetailHeaderView                 *header;
@property(nonatomic, strong) KLGoodDetailBoomView                   *bootomView;
@property(nonatomic, strong) KLGoodDetailModel                     *goooDetailModel;
@property(nonatomic, strong) NSMutableArray                     *dataSouce;
@property(nonatomic, strong) STNoresultView                     *noResultView;
@end

@implementation KLGoodDetailViewController
#pragma mark --vc 生命周期
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.title = @"商品详情";
    [self st_setRightItemWithTitle:@"分享" titleColor:[UIColor whiteColor]];
    [self addNotifacations];

    [self confiBottomView];
    
    self.automaticallyAdjustsScrollViewInsets = NO;
    if (IOS11 && [self.tableView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
        [self.tableView setContentInsetAdjustmentBehavior:@(2)];
    }
    self.tableView.frame = CGRectMake(0, [KLUtils navgationBarBootom], UIScreenWidth, self.bootomView.top -[KLUtils navgationBarBootom] );
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        [self sendGoodDetailRequest];
    }];
    [self.tableView.mj_header beginRefreshing];
    self.noResultView = [[STNoresultView alloc] initWithFrame:CGRectMake(0, self.tableView.tableHeaderView.height + 120, UIScreenWidth, 350)
                                                        title:@"暂无评论"
                                                  buttonTitle:@""
                                                 buttonHandle:^(NSString *titleString) {
                                                     
                                                 }];
    self.noResultView.hidden = YES;
    self.tableView.tableFooterView = self.noResultView;
    // Do any additional setup after loading the view.
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
#pragma mark --Notifacation
- (void)addNotifacations{
    
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(youShouldRefresh)
                                                 name:UIApplicationWillEnterForegroundNotification
                                               object:nil];
    
}
- (void)youShouldRefresh{
    [self.tableView.mj_header beginRefreshing];
}
- (void)dealloc{
    
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
#pragma mark --subView
- (void)confiBottomView{
    //底部
    __weak typeof(self) weakSelf =  self;
    self.bootomView = [[KLGoodDetailBoomView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 49) handle:^(NSString *title) {
        [weakSelf onSelectedBootomButtonWithTitle:title];
    }];
    self.bootomView.backgroundColor = [UIColor whiteColor];
    [self.bootomView st_showTopShadow];
    self.bootomView.top = [KLUtils tabBarTop];
    [self.view addSubview:self.bootomView];
}
- (void)configSubView{
    self.tableView.backgroundColor = [UIColor clearColor];

    //baner
    if (!self.adverView) {
            self.adverView = [[STAdvertingScrollView alloc] initWithFrame:CGRectMake(0, [KLUtils navgationBarBootom], UIScreenWidth, KLIconHeaderHeight) andWithArray:@[@"banner",@"banner",@"banner",@"banner",@"banner"] handle:^(NSInteger num) {
        
            }];
            self.adverView.pageControll.bottom = self.adverView.height - 15;
            self.adverView.pageControll.currentPageIndicatorTintColor = [UIColor whiteColor];
            self.adverView.pageControll.pageIndicatorTintColor = KL_BlueBackGroundColor;
            self.adverView.pageControll.width = self.adverView.dataSouce.count * 10;
            self.adverView.pageControll.centerX = UIScreenWidth / 2;
            self.adverView.canAutoScroll = YES;
            self.adverView.time = 3;
            self.adverView.userInteractionEnabled = YES;
            [self.view insertSubview:self.adverView atIndex:0];
    }
    
    
    self.header = [[KLGoodDetailHeaderView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 200)];
    self.header.delegate = self;
    self.tableView.tableHeaderView = self.header;
    self.header.hitTestView = self.adverView;
    self.header.clipsToBounds = YES;
}
#pragma --mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    return self.dataSouce.count?1:0;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return self.dataSouce.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    [self tableView:tableView cellForRowAtIndexPath:indexPath];
    KLCommentModel * mdoel = self.dataSouce[indexPath.row];
    return  mdoel.height;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    return 54;
}
- (UIView*)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView * header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, UIScreenWidth, 54)];
    header.backgroundColor = KL_backgroundColor;
    STLabel * titleLable = [[STLabel alloc] initWithFrame:CGRectMake(0, 10, UIScreenWidth - 0, 44)
                                                     text:[NSString stringWithFormat:@"  全部评论(%ld)",self.dataSouce.count]
                                                textColor:KL_firstTextColor
                                                     font:15
                                              isSizetoFit:NO
                                            textAlignment:NSTextAlignmentLeft];
    titleLable.backgroundColor = [UIColor whiteColor];
    [header addSubview:titleLable];
    return header;
}
- (UIView*)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [UIView new];
}
- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    static NSString * reuseIdentifier =  @"cell";
    KLCommentTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
    if (!cell) {
        cell = [[KLCommentTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:reuseIdentifier];
        
    }
    cell.commentModel = self.dataSouce[indexPath.row];
    return cell;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (scrollView == self.tableView) {
        //滑动动画
        UIEdgeInsets inset = self.tableView.contentInset;
        //NSLog(@"------%f",inset.top);
        CGFloat y = self.tableView.contentOffset.y;
      //  NSLog(@"滑动了%f",y);
        if (y  > 0) {
            self.adverView.top =  - 0.2 * y + 64;
        }else{
            self.adverView.top = - y + 64;
        }
        
    }
}
#pragma --mark UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    [self.tableView deselectRowAtIndexPath:indexPath animated:NO];
}
#pragma mark --KLGoodDetailHeaderViewDelegate
- (void)onSelectedContactButton{

    NSString * phone = self.goooDetailModel.shops.phone ;
    BOOL isSelf =  [[STUserManger defult].phone isEqualToString:phone];
    if (isSelf) {
        [SVProgressHUD showInfoWithStatus:@"这是你自己发布的产品哟"];
        return;
    }
    KLMessageChatViewController * vc = [[KLMessageChatViewController alloc] initWithConversationChatter:phone conversationType:EMConversationTypeChat];
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)onSelectedGoodDetailButton{
    KLGoodBuyDetailViewController * vc = [KLGoodBuyDetailViewController new];
    vc.model = self.goooDetailModel;
    [self.navigationController pushViewController:vc animated:YES];
}
#pragma mark --Action Method
- (void)st_rightBarAction:(id)sender{
    KLSharePresentController * vc = [[KLSharePresentController alloc] initWithHandle:^(NSString *chosedIde) {
        if([chosedIde isEqualToString:@"微信好友"]){
            [self shareToGoodFriend];
        }else{
            [self shareFriendCircle];
        }
    }];
    [self presentViewController:vc animated:NO completion:nil];
}
- (void)onSelectedBootomButtonWithTitle:(NSString*)title{
    if (!self.goooDetailModel) {
        //如果进入页面加载失败，没有goodtetailModel 则先请求数据
        [self sendGoodDetailRequest];
        return;
    }
    if ([title isEqualToString:@"收藏"]) {
        //[self sendCollectionRequest];
    }
    
    if ([title isEqualToString:@"加入购物车"]) {
        if (self.goooDetailModel.classification.integerValue == 3) {
            [SVProgressHUD showInfoWithStatus:@"匀加速折扣商品只能立刻购买哟"];
            return;
        }
        if (self.goooDetailModel.classification.integerValue == 4) {
            [SVProgressHUD showInfoWithStatus:@"菜园子商品不能加入购物车哟"];
            return;
        }
        if ([self.header.autoView.currentNum integerValue] == 0) {
            [SVProgressHUD showErrorWithStatus:@"请选择数量"];
            return;
        }
        if (self.goooDetailModel.stock.integerValue <1) {
            [SVProgressHUD showInfoWithStatus:@"商品已售罄"];
            return;
            
        }
        [self sendAddToCarRequest];
        
    }
    if ([title isEqualToString:@"立刻购买"]  && self.goooDetailModel) {
        if (self.goooDetailModel.stock.integerValue <1) {
            [SVProgressHUD showInfoWithStatus:@"商品已售罄"];
            return;
            
        }
        if (self.goooDetailModel.classification.integerValue == 3) {
            //匀加速
            KLSepeedBuyViewController * vc = [KLSepeedBuyViewController new];
            vc.model = self.goooDetailModel;
             [self.navigationController pushViewController:vc animated:YES];
            
        }else{
            
            KLBuyNowViewController * vc= [KLBuyNowViewController new];
            self.goooDetailModel.num = [self.header.autoView.currentNum integerValue];
            vc.dataSouce = @[@[self.goooDetailModel]];
            [self.navigationController pushViewController:vc animated:YES];
        }

    }
    
}
#pragma mark --Private Method
- (void)reloadData{
    self.header.detailModel = self.goooDetailModel;
    self.adverView.imageUrlsArray = self.goooDetailModel.cover_map;
   // [self.bannerImageView sd_setImageWithURL:[NSURL URLWithString:self.goooDetailModel.cover_map.firstObject] placeholderImage:self.bannerImageView.image];
    self.noResultView.hidden = self.dataSouce.count;
    if (self.dataSouce.count) {
        self.tableView.tableFooterView = nil;
    }else{
        self.tableView.tableFooterView = self.noResultView;
    }
    self.noResultView.top = self.tableView.tableHeaderView.height  +120;
    if (self.goooDetailModel.classification.integerValue == 3) {
        
    }
    [self.tableView reloadData];
}
#pragma mark --NetWork Method
- (void)sendGoodDetailRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@",serviceUrl,@"/api/goods/goodsinfo"];
    if (self.goodID) {
        [dic setObject:self.goodID forKey:@"goods_id"];
    }
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                 NSDictionary * dataDic =  responseObject[@"data"];
                                                 [self configSubView];
                                                 if ([dataDic.allKeys containsObject:@"info"]) {
                                                     self.goooDetailModel = [KLGoodDetailModel mj_objectWithKeyValues:dataDic[@"info"]];
                                                     
                                                     self.goooDetailModel.shops = [KLShopModel mj_objectWithKeyValues:dataDic[@"info"][@"shops"]];
                                                 }
                                                 if ([dataDic.allKeys containsObject:@"comment"]) {
                                                     NSArray * comments = dataDic[@"comment"];
                                                     self.dataSouce = [NSMutableArray new];
                                                     for (NSDictionary * commentDic in comments) {
                                                         KLCommentModel * coomentModel = [KLCommentModel mj_objectWithKeyValues:commentDic];
                                                         [self.dataSouce addObject:coomentModel];
                                                     }
                                                     
                                                 }
                                                 [self reloadData];
                                                 [self.tableView.mj_header endRefreshing];
                                                 [SVProgressHUD dismiss];
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 [self reloadData];
                                                 [self.tableView.mj_header endRefreshing];
                                                 
                                             }];
}

//加入购物车
- (void)sendAddToCarRequest{
    [SVProgressHUD showWithStatus:@"请稍后"];
    NSMutableDictionary * dic = [NSMutableDictionary new];
    NSString * url = [NSString stringWithFormat:@"%@%@%@",serviceUrl,@"/api/user/addshopping",[NSString stringWithFormat:@"?token=%@",[STUserManger defult].token]];
    if (self.goodID) {
        [dic setObject:self.goodID forKey:@"goods_id"];
    }
    if ([self.header.autoView.currentNum integerValue] != 0) {
        [dic setObject:self.header.autoView.currentNum forKey:@"number"];
    }
    if (self.goooDetailModel) {
        [dic setObject:self.goooDetailModel.shops.gategoryID forKey:@"shops_id"];
    }
    [dic setObject:@"1" forKey:@"goods_type"];
    [[STNetWrokManger defaultClient] requestWithPath:url
                                              method:STHttpRequestTypePost
                                          parameters:dic
                                             success:^(NSURLSessionDataTask *operation, id responseObject) {
                                                 
                                                  [SVProgressHUD dismiss];
                                                 [SVProgressHUD showSuccessWithStatus:@"加入购物车成功"];
                                                
                                             } failure:^(NSString *stateCode, STError *error) {
                                                 [SVProgressHUD dismiss];
                                                 [SVProgressHUD showErrorWithStatus:error.desc];
                                                 
                                             }];
}
#pragma mark --Private Method
//微信朋友圈
- (void)shareFriendCircle{
    
    
    NSString * url = [NSString stringWithFormat:@"http://jshjkd.com/gold/public/home/web/friend?uid=%@",[STUserManger defult].userID];
    url = @"https://www.pgyer.com/tJmO";
    SendMessageToWXReq  *req = [SendMessageToWXReq new];
    req.scene = WXSceneTimeline;
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = @"昆仑科技";
    //分享标题 urlMessage.description = kLinkDescription;//分享描述
    [urlMessage setThumbImage:[UIImage imageNamed:@"logoiPadApp_76pt"]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = url;//分享链接 //完成发送对象实例
    urlMessage.mediaObject = webObj;
    req.message = urlMessage; //发送分享信息
    [WXApi sendReq:req];
    
    
}
//微信好友
- (void)shareToGoodFriend{
    NSString * url = [NSString stringWithFormat:@"http://jshjkd.com/gold/public/home/web/share?tid=%@",[STUserManger defult].userID];
    url = @"https://www.pgyer.com/tJmO";
    SendMessageToWXReq  *req = [SendMessageToWXReq new];
    req.scene = WXSceneSession;
    WXMediaMessage *urlMessage = [WXMediaMessage message];
    urlMessage.title = @"昆仑科技";
    //分享标题 urlMessage.description = kLinkDescription;//分享描述
    [urlMessage setThumbImage:[UIImage imageNamed:@"logoiPadApp_76pt"]];//分享图片,使用SDK的setThumbImage方法可压缩图片大小
    //创建多媒体对象
    WXWebpageObject *webObj = [WXWebpageObject object];
    webObj.webpageUrl = url;//分享链接 //完成发送对象实例
    urlMessage.mediaObject = webObj;
    req.message = urlMessage; //发送分享信息
    [WXApi sendReq:req];
}
@end

